package solr;

import cn.hutool.core.util.ArrayUtil;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.beans.DocumentObjectBinder;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.FieldStatsInfo;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import java.io.IOException;
import java.util.*;

public class SearchService {
	
    private SolrClient _SolrClient;

	/**
     * 指定一个检索核心
     * @param url
     */
    public SearchService(String url) {
    	this._SolrClient = new HttpSolrClient.Builder(url).withConnectionTimeout(10000).withSocketTimeout(60000).build();
    }

    /**
     * 高亮查询，返回实体集合
     * 注意:需要在实体中使用注解
     */
	@SuppressWarnings("unchecked")
	public <T> List<T> highLightQuery(SearchEntity searchEntity, Class<T> type) throws SolrServerException, IOException {
    	
        SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        if (searchEntity.getHl() != null) {
            query.setHighlight(true);//开启高亮
            query.setParam("hl.preserveMulti", true);//高亮所有多值字段
            query.setHighlightFragsize(100000);//每个分片的最大长度，默认是一个分片
            List<String> highlightFields = searchEntity.getHl();
            //设置高亮字段
            for (int i = 0; i < highlightFields.size(); i++) {
                query.addHighlightField(highlightFields.get(i));
            }
            if(searchEntity.getHl_pre()!=null && searchEntity.getHl_post()!=null){
            	query.setHighlightSimplePre(searchEntity.getHl_pre());//渲染标签前缀
            	query.setHighlightSimplePost(searchEntity.getHl_post());//渲染标签后缀
            }
        }
        //排序
        if (searchEntity.getSort() != null) {
        	List<String> sorts = searchEntity.getSort();
        	String[] sort = null;
            for (int i = 0; i < sorts.size(); i++) {
                sort = sorts.get(i).split(":");
                if ("asc".equals(sort[1])) {
                    query.addSort(sort[0], ORDER.asc);
                } else if ("desc".equals(sort[1])) {
                    query.addSort(sort[0], ORDER.desc);
                }
            }
        }
        query.setStart(searchEntity.getStart());
        query.setRows(searchEntity.getRows());
        query.set("wt", "json");//返回类型
        query.set("indent", "on");
        if (searchEntity.getFl() != null) {
        	List<String> fields = searchEntity.getFl();
        	for (int i = 0; i < fields.size(); i++) {
        		query.addField(fields.get(i));
			}
        }

		QueryResponse response = this._SolrClient.query(query);// 查询并返回结果
//		response.getBeans(type);
		SolrDocumentList documents = response.getResults();
		String uniqueField = searchEntity.getUniqueField();
		SolrDocumentList documentsHl = new SolrDocumentList();
		Map<String, Map<String, List<String>>> map = response.getHighlighting();
		List<String> hl = searchEntity.getHl();
		SolrDocument document = null;
		Collection<String> fieldNames = null;
		for (int i = 0; i < documents.size(); i++) {
			document = documents.get(i);
			fieldNames = document.getFieldNames();
			for (String field : fieldNames) {
				if (hl != null && hl.contains(field) && uniqueField!=null){
					if (null != map.get(document.getFieldValue(uniqueField)).get(field)) {
						Object obj = document.getFieldValue(field);
						if(obj instanceof List){
							document.setField(field,
									ArrayUtil.join(map.get(document.getFieldValue(uniqueField)).get(field),";;"));
						}else{
							document.setField(field,
									map.get(document.getFieldValue(uniqueField)).get(field).get(0).toString());
						}
					}
				}else{
					if (null != document.getFieldValues(field)) {
						Object obj = document.getFieldValue(field);
						if(obj instanceof List){
							document.setField(field,
									ArrayUtil.join(obj,";;"));
						}
					}
				}
			}
			documentsHl.add(document);
		}
		documents = documentsHl;
		DocumentObjectBinder binder = new DocumentObjectBinder();
		List<T> list = binder.getBeans(type, documents);
        return list;
    }
	
	/**
	 * 高亮查询并返回map集合
	 */
	@SuppressWarnings("unchecked")
	public List<LinkedHashMap<String, String>> highLightQueryResultMap(SearchEntity searchEntity) throws SolrServerException, IOException {
    	
        SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        if (searchEntity.getHl() != null) {
            query.setHighlight(true);//开启高亮
            query.setParam("hl.preserveMulti", true);//高亮所有多值字段
            query.setHighlightFragsize(100000);//每个分片的最大长度，默认是一个分片
            List<String> highlightFields = searchEntity.getHl();
            //设置高亮字段
            for (int i = 0; i < highlightFields.size(); i++) {
                query.addHighlightField(highlightFields.get(i));
            }
            if(searchEntity.getHl_pre()!=null && searchEntity.getHl_post()!=null){
            	query.setHighlightSimplePre(searchEntity.getHl_pre());//渲染标签前缀
            	query.setHighlightSimplePost(searchEntity.getHl_post());//渲染标签后缀
            }
        }
        //排序
        if (searchEntity.getSort() != null) {
        	List<String> sorts = searchEntity.getSort();
        	String[] sort = null;
            for (int i = 0; i < sorts.size(); i++) {
                sort = sorts.get(i).split(":");
                if ("asc".equals(sort[1])) {
                    query.addSort(sort[0], ORDER.asc);
                } else if ("desc".equals(sort[1])) {
                    query.addSort(sort[0], ORDER.desc);
                }
            }
        }
        query.setStart(searchEntity.getStart());
        query.setRows(searchEntity.getRows());
        query.set("wt", "json");//返回类型
        query.set("indent", "on");
        if (searchEntity.getFl() != null) {
        	List<String> fields = searchEntity.getFl();
        	for (int i = 0; i < fields.size(); i++) {
        		query.addField(fields.get(i));
			}
        }

		QueryResponse response = this._SolrClient.query(query);// 查询并返回结果
		SolrDocumentList documents = response.getResults();
		String uniqueField = searchEntity.getUniqueField();
		List<LinkedHashMap<String, String>> result = new ArrayList<LinkedHashMap<String,String>>();
		LinkedHashMap<String, String> restultmap = null;
		Map<String, Map<String, List<String>>> map = response.getHighlighting();
		List<String> hl = searchEntity.getHl();
		SolrDocument document = null;
		Collection<String> fieldNames = null;
		for (int i = 0; i < documents.size(); i++) {
			restultmap = new LinkedHashMap<String, String>();
			document = documents.get(i);
			fieldNames = document.getFieldNames();
			for (String field : fieldNames) {
				if (hl != null && hl.contains(field) && uniqueField!=null){
					if (null != map.get(document.getFieldValue(uniqueField)).get(field)) {
						Object obj = document.getFieldValue(field);
						if(obj instanceof List){
							restultmap.put(field, ArrayUtil.join(map.get(document.getFieldValue(uniqueField)).get(field),";;"));
						}else{
							restultmap.put(field, map.get(document.getFieldValue(uniqueField)).get(field).get(0).toString());
						}
					}else {
						restultmap.put(field, "");
					}
				}else{
					if (null != document.getFieldValues(field)) {
						Object obj = document.getFieldValue(field);
						if(obj instanceof List){
							restultmap.put(field, ArrayUtil.join(obj,";;"));
						}else{
							restultmap.put(field, obj.toString());
						}
					}else{
						restultmap.put(field, "");
					}
				}
			}
			result.add(restultmap);
		}
        return result;
    }
    
	/**
     * 计算查询总数
     */
    public int searchCount(SearchEntity searchEntity) throws SolrServerException, IOException {
    	SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        query.set("wt", "json");//返回类型
        QueryResponse response = this._SolrClient.query(query);//查询并返回结果
        return (int) response.getResults().getNumFound();
    }
	
    /**
     * 自定义权重高亮查询，返回实体集合
     * 注意:需要在实体中使用注解
     */
    @SuppressWarnings("unchecked")
	public <T> List<T> defTypeHighLightQuery(SearchEntity searchEntity, Class<T> type) throws SolrServerException, IOException {
        
    	SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        if (searchEntity.getHl() != null) {
            query.setHighlight(true);//开启高亮
            query.setParam("hl.preserveMulti", true);//高亮所有多值字段
            query.setHighlightFragsize(100000);//每个分片的最大长度，默认是一个分片
            List<String> highlightFields = searchEntity.getHl();
            //设置高亮字段
            for (int i = 0; i < highlightFields.size(); i++) {
                query.addHighlightField(highlightFields.get(i));
            }
            if(searchEntity.getHl_pre()!=null && searchEntity.getHl_post()!=null){
            	query.setHighlightSimplePre(searchEntity.getHl_pre());//渲染标签前缀
            	query.setHighlightSimplePost(searchEntity.getHl_post());//渲染标签后缀
            }
        }
        //排序
        if (searchEntity.getSort() != null) {
        	List<String> sorts = searchEntity.getSort();
        	String[] sort = null;
            for (int i = 0; i < sorts.size(); i++) {
                sort = sorts.get(i).split(":");
                if ("asc".equals(sort[1])) {
                    query.addSort(sort[0], ORDER.asc);
                } else if ("desc".equals(sort[1])) {
                    query.addSort(sort[0], ORDER.desc);
                }
            }
        }
        query.setStart(searchEntity.getStart());
        query.setRows(searchEntity.getRows());
        query.set("wt", "json");//返回类型
        query.set("indent", "on");
        if (searchEntity.getFl() != null) {
        	List<String> fields = searchEntity.getFl();
        	for (int i = 0; i < fields.size(); i++) {
        		query.addField(fields.get(i));
			}
        }
        
        query.set("defType", "edismax");
        if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())){
        	query.set("qf", searchEntity.getQf());
        	query.set("tie", "1.0");
        }
        
		if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}
		QueryResponse response = this._SolrClient.query(query);// 查询并返回结果
		SolrDocumentList documents = response.getResults();
		String uniqueField = searchEntity.getUniqueField();
		SolrDocumentList documentsHl = new SolrDocumentList();
		Map<String, Map<String, List<String>>> map = response.getHighlighting();
		List<String> hl = searchEntity.getHl();
		SolrDocument document = null;
		Collection<String> fieldNames = null;
		for (int i = 0; i < documents.size(); i++) {
			document = documents.get(i);
			fieldNames = document.getFieldNames();
			for (String field : fieldNames) {
				if (hl != null && hl.contains(field) && uniqueField!=null){
					if (null != map.get(document.getFieldValue(uniqueField)).get(field)) {
						Object obj = document.getFieldValue(field);
						if(obj instanceof List){
							document.setField(field,
									ArrayUtil.join(map.get(document.getFieldValue(uniqueField)).get(field),";;"));
						}else{
							document.setField(field,
									map.get(document.getFieldValue(uniqueField)).get(field).get(0).toString());
						}
					}
				}else{
					if (null != document.getFieldValues(field)) {
						Object obj = document.getFieldValue(field);
						if(obj instanceof List){
							document.setField(field,
									ArrayUtil.join((List<String>)obj,";;"));
						}
					}
				}
			}
			documentsHl.add(document);
		}
		documents = documentsHl;
		DocumentObjectBinder binder = new DocumentObjectBinder();
		List<T> list = binder.getBeans(type, documents);
        return list;
    }
    
    /**
	 * 自定义权重高亮查询并返回map集合
	 */
	@SuppressWarnings("unchecked")
	public LinkedHashMap<Object, Object> defTypeHighLightQueryResultMap(SearchEntity searchEntity) throws SolrServerException, IOException {
    	
        SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        if (searchEntity.getHl() != null) {
            query.setHighlight(true);//开启高亮
            query.setParam("hl.preserveMulti", true);//高亮所有多值字段
            query.setHighlightFragsize(100000);//每个分片的最大长度，默认是一个分片
            List<String> highlightFields = searchEntity.getHl();
            //设置高亮字段
            for (int i = 0; i < highlightFields.size(); i++) {
                query.addHighlightField(highlightFields.get(i));
            }
            if(searchEntity.getHl_pre()!=null && searchEntity.getHl_post()!=null){
            	query.setHighlightSimplePre(searchEntity.getHl_pre());//渲染标签前缀
            	query.setHighlightSimplePost(searchEntity.getHl_post());//渲染标签后缀
            }
        }
        //排序
        if (searchEntity.getSort() != null) {
        	List<String> sorts = searchEntity.getSort();
        	String[] sort = null;
            for (int i = 0; i < sorts.size(); i++) {
                sort = sorts.get(i).split(":");
                if ("asc".equals(sort[1])) {
                    query.addSort(sort[0], ORDER.asc);
                } else if ("desc".equals(sort[1])) {
                    query.addSort(sort[0], ORDER.desc);
                }
            }
        }
        //多核心
        if (searchEntity.getShards()!=null && searchEntity.getShards().size()>0) {
        	String shards = ArrayUtil.join(searchEntity.getShards(),",");
            query.set("shards", shards);
        }
        
        query.setStart(searchEntity.getStart());
        query.setRows(searchEntity.getRows());
        query.set("wt", "json");//返回类型
        query.set("indent", "on");
        if (searchEntity.getFl() != null) {
        	List<String> fields = searchEntity.getFl();
        	for (int i = 0; i < fields.size(); i++) {
        		query.addField(fields.get(i));
			}
        }

        query.set("defType", "edismax");
        if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())){
        	query.set("qf", searchEntity.getQf());
        	query.set("tie", "1.0");
        }
        
		if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}
		
		QueryResponse response = this._SolrClient.query(query);// 查询并返回结果
		SolrDocumentList documents = response.getResults();
		String uniqueField = searchEntity.getUniqueField();
		List<LinkedHashMap<String, String>> result = new ArrayList<LinkedHashMap<String,String>>();
		LinkedHashMap<String, String> restultmap = null;
		Map<String, Map<String, List<String>>> map = response.getHighlighting();
		List<String> hl = searchEntity.getHl();
		SolrDocument document = null;
		Collection<String> fieldNames = null;
		for (int i = 0; i < documents.size(); i++) {
			restultmap = new LinkedHashMap<String, String>();
			document = documents.get(i);
			fieldNames = document.getFieldNames();
			for (String field : fieldNames) {
				if (hl != null && hl.contains(field) && uniqueField!=null){
					if (null != map.get(document.getFieldValue(uniqueField)).get(field)) {
						Object obj = document.getFieldValue(field);
						if(obj instanceof List){
							restultmap.put(field, ArrayUtil.join(map.get(document.getFieldValue(uniqueField)).get(field),";;"));
						}else{
							restultmap.put(field, map.get(document.getFieldValue(uniqueField)).get(field).get(0).toString());
						}
					}else {
						restultmap.put(field, "");
					}
				}else{
					if (null != document.getFieldValues(field)) {
						Object obj = document.getFieldValue(field);
						if(obj instanceof List){
							restultmap.put(field, ArrayUtil.join(obj,";;"));
						}else{
							restultmap.put(field, obj.toString());
						}
					}else{
						restultmap.put(field, "");
					}
				}
			}
			result.add(restultmap);
		}
		
		LinkedHashMap<Object, Object> returnMap = new LinkedHashMap<Object, Object>();
        returnMap.put("result", result);
        returnMap.put("total", documents.getNumFound());
        return returnMap;
    }
    
    /**
     * 计算自定义权重查询总数
     */
	public int defTypeSearchCount(SearchEntity searchEntity) throws SolrServerException, IOException {

		SolrQuery query = new SolrQuery();

		query.setQuery(searchEntity.getQ());

		if (searchEntity.getFq() != null) {
			List<String> fq = searchEntity.getFq();
			for (int i = 0; i < fq.size(); i++) {
				String fq_str = fq.get(i);
				if (fq_str.indexOf("year:\"[") != -1) {
					fq_str = fq_str.replaceAll("\"", "");
				}
				query.addFilterQuery(fq_str);
			}
		}

		query.set("wt", "json");// 返回类型

		query.set("defType", "edismax");
		if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())) {
			query.set("qf", searchEntity.getQf());
			query.set("tie", "1.0");
		}
		
		if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}
		// 查询并返回结果
		QueryResponse response = _SolrClient.query(query);
		return (int) response.getResults().getNumFound();
    }
    
    
    /**
     * 更新数据索引
     * 注意:需要在实体中使用注解，实体中没有注解时无法使用
     */
    public <T> void updateSolr(T entity, Class<T> type) throws IOException, SolrServerException{
    	this._SolrClient.addBean(entity);
    	this._SolrClient.commit();
    }
    
    /**
     * 根据id删除数据索引
     */
    public void deleteSolr(String id) throws SolrServerException, IOException{
    	this._SolrClient.deleteById(id);
    	this._SolrClient.commit();
    }
    
    
    /**
     * 多核心查询多个分面集合
     */
    public LinkedHashMap<Object, LinkedHashMap<Object, Object>> multiCoreSearchFacetCountList(SearchEntity searchEntity) throws SolrServerException, IOException {
        
    	LinkedHashMap<Object, LinkedHashMap<Object, Object>> flMap = new LinkedHashMap<>();
    	if(searchEntity.getFacetFields() == null){
    		return flMap;
    	}
    	
    	SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        if (searchEntity.getShards() != null && searchEntity.getShards().size() > 0) {
			String shards = ArrayUtil.join(searchEntity.getShards(),",");
			query.set("shards", shards);
		}
        
        query.setFacet(true);
        query.setFacetMinCount(1);
        query.setFacetLimit(searchEntity.getFacetLimit());
    	List<String> facetFields = searchEntity.getFacetFields();
    	for (int i = 0; i < facetFields.size(); i++) {
            query.addFacetField(facetFields.get(i));
        }
    	query.addField(facetFields.get(0));
        
        query.set("wt", "json");//返回类型
        query.set("indent", "on");
    	
    	
        LinkedHashMap<Object, Object> flLMap;
        String facetField = "";
        QueryResponse response = this._SolrClient.query(query);//查询并返回结果
        List<FacetField> facetlist = response.getFacetFields();
        for (int i = 0; i < facetlist.size(); i++) {
            flLMap = new LinkedHashMap<>();
            FacetField facet = facetlist.get(i);
            facetField = facet.getName();
            List<Count> list = facet.getValues();
            if (null != list) {
                for (Count count : list) {
                    flLMap.put(count.getName(), count.getCount());
                }
            }
            flMap.put(facetField, flLMap);
        }
        return flMap;
    }
    
    /**
     * 多核心自定义权重查询多个分面集合
     */
    public LinkedHashMap<Object, LinkedHashMap<Object, Object>> multiCoreDefTypeSearchFacetCountList(SearchEntity searchEntity) throws SolrServerException, IOException {
    	
    	LinkedHashMap<Object, LinkedHashMap<Object, Object>> flMap = new LinkedHashMap<>();
    	if(searchEntity.getFacetFields() == null){
    		return flMap;
    	}
    	
    	SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        if (searchEntity.getShards() != null && searchEntity.getShards().size() > 0) {
			String shards = ArrayUtil.join(searchEntity.getShards(),",");
			query.set("shards", shards);
		}
        
        query.setFacet(true);
        query.setFacetMinCount(1);
        query.setFacetLimit(searchEntity.getFacetLimit());
    	List<String> facetFields = searchEntity.getFacetFields();
    	for (int i = 0; i < facetFields.size(); i++) {
            query.addFacetField(facetFields.get(i));
        }
//    	query.addField(facetFields.get(0));
        
        query.set("wt", "json");//返回类型
        query.set("indent", "on");
        
        query.set("defType", "edismax");
        if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())){
        	query.set("qf", searchEntity.getQf());
        	query.set("tie", "1.0");
        }
        
		if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}

        LinkedHashMap<Object, Object> flLMap;
        String facetField = "";
        QueryResponse response = this._SolrClient.query(query);//查询并返回结果
        List<FacetField> facetlist = response.getFacetFields();
        for (int i = 0; i < facetlist.size(); i++) {
            flLMap = new LinkedHashMap<>();
            FacetField facet = facetlist.get(i);
            facetField = facet.getName();
            List<Count> list = facet.getValues();
            if (null != list) {
                for (Count count : list) {
                    flLMap.put(count.getName(), count.getCount());
                }
            }
            flMap.put(facetField, flLMap);
        }
        return flMap;
    }
    
    /**
     * 多核心查询单个分面(按分面聚类出的值排序)
     */
    public LinkedHashMap<Object, Object> multiCoreDefTypeSearchFacetCountY(SearchEntity searchEntity) throws SolrServerException, IOException {
        
    	LinkedHashMap<Object, Object> flMap = new LinkedHashMap<Object, Object>();
    	if(searchEntity.getFacetField() == null){
    		return flMap;
    	}
    	
    	SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        if (searchEntity.getShards() != null && searchEntity.getShards().size() > 0) {
			String shards = ArrayUtil.join(searchEntity.getShards(),",");
			query.set("shards", shards);
		}
        
        query.setFacet(true);
        query.setFacetMinCount(1);
		query.setFacetLimit(Integer.MAX_VALUE);
		query.setFacetSort(searchEntity.getFacetField());
		query.addFacetField(searchEntity.getFacetField());
		query.addField(searchEntity.getFacetField());
		
		query.set("wt", "json");// 返回类型
		
		if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())){
        	query.set("defType", "edismax");
        	query.set("qf", searchEntity.getQf());
        	query.set("tie", "1.0");
        	
        	if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
    			query.set("boost", searchEntity.getBoost());
    		}
        }
		
        QueryResponse response = this._SolrClient.query(query);//查询并返回结果
        FacetField facet = response.getFacetField(searchEntity.getFacetField());
        List<Count> list = facet.getValues();
        if (null != list) {
            Integer size = list.size() - 1;
            int topnum = searchEntity.getFacetLimit();
            for (int i = size; i > -1 && topnum > 0; i--, topnum--) {
                Count c = list.get(i);
                flMap.put(c.getName(), c.getCount());
            }
        }
        return flMap;
    }
    
    /**
     * 多核心查询单个分面(按分面聚类出的值的数量排序，默认排序)
     */
    public LinkedHashMap<Object, Object> multiCoreSearchFacetCount(SearchEntity searchEntity) throws SolrServerException, IOException {
    	
    	LinkedHashMap<Object, Object> flMap = new LinkedHashMap<Object, Object>();
    	if(searchEntity.getFacetField() == null){
    		return flMap;
    	}
    	
    	SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        if (searchEntity.getShards() != null && searchEntity.getShards().size() > 0) {
			String shards = ArrayUtil.join(searchEntity.getShards(),",");
			query.set("shards", shards);
		}
        
        query.setFacet(true);
        query.setFacetMinCount(1);
        query.setFacetLimit(searchEntity.getFacetLimit());
    	query.addFacetField(searchEntity.getFacetField());
    	query.addField(searchEntity.getFacetField());

        query.set("wt", "json");//返回类型
        query.set("indent", "on");
        
        query.set("defType", "edismax");
        if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())){
        	query.set("qf", searchEntity.getQf());
        	query.set("tie", "1.0");
        }
        
		if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}
        
        QueryResponse response = this._SolrClient.query(query);//查询并返回结果
        FacetField facet = response.getFacetField(searchEntity.getFacetField());
        List<Count> list = facet.getValues();
        if (null != list) {
            for (Count count : list) {
                flMap.put(count.getName(), count.getCount());
            }
        }
        return flMap;
    }

    /**
     * 多核心查询单个分面(按分面聚类出的值排序)
     */
    public LinkedHashMap<Object, Object> multiCoreSearchFacetCountY(SearchEntity searchEntity) throws SolrServerException, IOException {
        
    	LinkedHashMap<Object, Object> flMap = new LinkedHashMap<Object, Object>();
    	if(searchEntity.getFacetField() == null){
    		return flMap;
    	}
    	
    	SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        if (searchEntity.getShards() != null && searchEntity.getShards().size() > 0) {
			String shards = ArrayUtil.join(searchEntity.getShards(),",");
			query.set("shards", shards);
		}
        
        query.setFacet(true);
        query.setFacetMinCount(1);
		query.setFacetLimit(Integer.MAX_VALUE);
		query.setFacetSort(searchEntity.getFacetField());
		query.addFacetField(searchEntity.getFacetField());
		query.addField(searchEntity.getFacetField());
		
		query.set("wt", "json");// 返回类型
		
		query.set("defType", "edismax");
        if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())){
        	query.set("qf", searchEntity.getQf());
        	query.set("tie", "1.0");
        }
        
		if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}
		
        QueryResponse response = this._SolrClient.query(query);//查询并返回结果
        FacetField facet = response.getFacetField(searchEntity.getFacetField());
        List<Count> list = facet.getValues();
        if (null != list) {
            Integer size = list.size() - 1;
            int topnum = searchEntity.getFacetLimit();
            for (int i = size; i > -1 && topnum > 0; i--, topnum--) {
                Count c = list.get(i);
                flMap.put(c.getName(), c.getCount());
            }
        }
        return flMap;
		
    }
    
    /**
     * 一次查询多个分面(按分面聚类出的值的数量排序，默认排序)
     */
    public LinkedHashMap<Object, LinkedHashMap<Object, Object>> SearchFacetList(SearchEntity searchEntity) throws SolrServerException, IOException {
        
    	LinkedHashMap<Object, LinkedHashMap<Object, Object>> flMap = new LinkedHashMap<>();
    	if(searchEntity.getFacetFields() == null){
    		return flMap;
    	}
    	
    	SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        query.setFacet(true);
        query.setFacetMinCount(1);
        query.setFacetLimit(searchEntity.getFacetLimit());
        List<String> facetFields = searchEntity.getFacetFields();
    	for (int i = 0; i < facetFields.size(); i++) {
            query.addFacetField(facetFields.get(i));
        }
    	query.addField(facetFields.get(0));

        query.set("wt", "json");//返回类型
        
        query.set("defType", "edismax");
        if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())){
        	query.set("qf", searchEntity.getQf());
        	query.set("tie", "1.0");
        }
        
		if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}
        
        LinkedHashMap<Object, Object> flLMap;
        String facetField = "";
        QueryResponse response = this._SolrClient.query(query);//查询并返回结果
        List<FacetField> facetlist = response.getFacetFields();
        for (int i = 0; i < facetlist.size(); i++) {
            flLMap = new LinkedHashMap<>();
            FacetField facet = facetlist.get(i);
            facetField = facet.getName();
            List<Count> list = facet.getValues();
            if (null != list) {
                for (Count count : list) {
                    flLMap.put(count.getName(), count.getCount());
                }
            }
            flMap.put(facetField, flLMap);
        }
        return flMap;
    }

    /**
     * 查询单个分面(按分面聚类出的值的数量排序，默认排序)
     */
    public LinkedHashMap<Object, Object> SearchFacet(SearchEntity searchEntity) throws SolrServerException, IOException {
    	
    	LinkedHashMap<Object, Object> flMap = new LinkedHashMap<Object, Object>();
    	if(searchEntity.getFacetField() == null){
    		return flMap;
    	}
    	
    	SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        query.setFacet(true);
        query.setFacetMinCount(1);
        query.setFacetLimit(searchEntity.getFacetLimit());
        query.addFacetField(searchEntity.getFacetField());
        query.addField(searchEntity.getFacetField());
        
        query.set("wt", "json");//返回类型
        
        query.set("defType", "edismax");
        if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())){
        	query.set("qf", searchEntity.getQf());
        	query.set("tie", "1.0");
        }
        
		if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}
        
        QueryResponse response = this._SolrClient.query(query);//查询并返回结果
        FacetField facet = response.getFacetField(searchEntity.getFacetField());
        List<Count> list = facet.getValues();
        if (null != list) {
            for (Count count : list) {
                flMap.put(count.getName(), count.getCount());
            }
        }
        return flMap;
    }


    /**
     * 查询单个分面(按分面聚类出的值排序)
     */
    public LinkedHashMap<Object, Object> SearchFacetY(SearchEntity searchEntity) throws SolrServerException, IOException {
        
    	LinkedHashMap<Object, Object> flMap = new LinkedHashMap<Object, Object>();
    	if(searchEntity.getFacetField() == null){
    		return flMap;
    	}
    	
    	SolrQuery query = new SolrQuery();
        
        query.setQuery(searchEntity.getQ());

        if (searchEntity.getFq() != null) {
        	List<String> fq = searchEntity.getFq();
            for (int i = 0; i < fq.size(); i++) {
                String fq_str = fq.get(i);
                if (fq_str.indexOf("year:\"[") != -1) {
                    fq_str = fq_str.replaceAll("\"", "");
                }
                query.addFilterQuery(fq_str);
            }
        }

        query.setFacet(true);
        query.setFacetMinCount(1);
        query.setFacetLimit(Integer.MAX_VALUE);
        query.setFacetSort(searchEntity.getFacetField());
        query.addFacetField(searchEntity.getFacetField());
        query.addField(searchEntity.getFacetField());
        
        query.set("wt", "json");//返回类型
        
        query.set("defType", "edismax");
        if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())){
        	query.set("qf", searchEntity.getQf());
        	query.set("tie", "1.0");
        }
        
		if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}

        QueryResponse response = this._SolrClient.query(query);//查询并返回结果
        FacetField facet = response.getFacetField(searchEntity.getFacetField());
        List<Count> list = facet.getValues();
        if (null != list) {
            Integer size = list.size() - 1;
            int topnum = searchEntity.getFacetLimit();
            for (int i = size; i > -1 && topnum > 0; i--, topnum--) {
                Count c = list.get(i);
                flMap.put(c.getName(), c.getCount());
            }
        }
        return flMap;
    }

    /**
	 * 统计查询
	 * @author 黄乾坤
	 * @Title statisticsQuery 
	 * @param queryString 查询条件 
	 * @param fq 查询过滤字符串
	 * @param statisticsField 统计字段集合
	 * @param statisticsFacetField 分面统计字段集合
	 * @return min=最小值 max=最大值 sum=总和 count=记录数 missing=结果集中的空值总条数 mean=平均数 stddev=标准差
     * @throws SolrServerException 
     * @throws IOException 
	 */
	public Map<String,Map<String,Map<Object, Map<Object,Object>>>> statisticsQuery(String queryString, String[] fq, String[] statisticsField, String[] statisticsFacetField) throws SolrServerException, IOException{
		
		if(statisticsField == null)return null;
		
		SolrQuery query = new SolrQuery();
		query.setQuery(queryString);
		
		if(fq != null){
			if (fq != null) {
	            for (int i = 0; i < fq.length; i++) {
	                String fq_str = fq[i];
	                if (fq[i].indexOf("year:\"[") != -1) {
	                    fq_str = fq[i].replaceAll("\"", "");
	                }
	                query.addFilterQuery(fq_str);
	            }
	        }
		}
		
		query.set("stats", true);
		for (int i = 0; i < statisticsField.length; i++) {
			query.add("stats.field", statisticsField[i]);
		}
		if(statisticsFacetField != null){
			for (int i = 0; i < statisticsFacetField.length; i++) {
				query.add("stats.facet", statisticsFacetField[i]);
			}
		}
		query.set("wt", "json");
		query.addField(statisticsFacetField[0]);
		
		QueryResponse response = this._SolrClient.query(query);//查询并返回结果
		Map<String,FieldStatsInfo> resultMap = response.getFieldStatsInfo();
		FieldStatsInfo statsInfo = null;
		Map<String,Map<String, Map<Object, Map<Object,Object>>>> map = new HashMap<String, Map<String,Map<Object,Map<Object,Object>>>>();
		Map<String, Map<Object, Map<Object,Object>>> facetMapResult = null;;
		Map<Object, Map<Object,Object>> mapList = null;
		Map<Object, Object> fMap = null;
		Map<String,List<FieldStatsInfo>> facetMap = null;
		List<FieldStatsInfo> fieldStatsInfoList = null;
		FieldStatsInfo fieldStatsInfo = null;
		for (String string : resultMap.keySet()) {
			statsInfo = resultMap.get(string);
			if(statisticsFacetField != null){
				facetMap = statsInfo.getFacets();
				if(facetMap!=null){
					facetMapResult = new HashMap<String, Map<Object,Map<Object,Object>>>();
					for (String str : facetMap.keySet()) {
						mapList = new HashMap<Object, Map<Object,Object>>();
						fieldStatsInfoList = facetMap.get(str);
						for (int j = 0; j < fieldStatsInfoList.size(); j++) {
							fieldStatsInfo = fieldStatsInfoList.get(j);
							fMap = new HashMap<Object, Object>();
							fMap.put("min", fieldStatsInfo.getMin());
							fMap.put("max", fieldStatsInfo.getMax());
							fMap.put("sum", fieldStatsInfo.getSum());
							fMap.put("count", fieldStatsInfo.getCount());
							fMap.put("missing", fieldStatsInfo.getMissing());
							fMap.put("mean", fieldStatsInfo.getMean());
							fMap.put("stddev", fieldStatsInfo.getStddev());
							mapList.put(fieldStatsInfo.getName(), fMap);
						}
						fMap = new HashMap<Object, Object>();
						fMap.put("min", statsInfo.getMin());
						fMap.put("max", statsInfo.getMax());
						fMap.put("sum", statsInfo.getSum());
						fMap.put("count", statsInfo.getCount());
						fMap.put("missing", statsInfo.getMissing());
						fMap.put("mean", statsInfo.getMean());
						fMap.put("stddev", statsInfo.getStddev());
						mapList.put("总计", fMap);
						facetMapResult.put(str, mapList);
					}
				}
				map.put(string, facetMapResult);
			}else{
				mapList = new HashMap<Object, Map<Object,Object>>();
				facetMapResult = new HashMap<String, Map<Object,Map<Object,Object>>>();
				fMap = new HashMap<Object, Object>();
				fMap.put("min", statsInfo.getMin());
				fMap.put("max", statsInfo.getMax());
				fMap.put("sum", statsInfo.getSum());
				fMap.put("count", statsInfo.getCount());
				fMap.put("missing", statsInfo.getMissing());
				fMap.put("mean", statsInfo.getMean());
				fMap.put("stddev", statsInfo.getStddev());
				mapList.put("总计", fMap);
				facetMapResult.put(statsInfo.getName(), mapList);
				map.put(string, facetMapResult);
			}
		}
		return map;
	}
    
	/**
	 * 多核心统计查询
	 * @author 黄乾坤
	 * @Title multiCoreStatisticsQuery 
	 * @param queryString
	 * @param shards
	 * @param fq
	 * @param statisticsField
	 * @param statisticsFacetField
	 * @return
	 * @throws SolrServerException
	 * @throws IOException 
	 */
	public Map<String,Map<String,Map<Object, Map<Object,Object>>>> multiCoreStatisticsQuery(String queryString,String shards, String[] fq, String[] statisticsField, String[] statisticsFacetField) throws SolrServerException, IOException{
		
		if(statisticsField == null)return null;
		
		SolrQuery query = new SolrQuery();
		query.setQuery(queryString);
		
		if (shards != null) {
            query.set("shards", shards);
        }
		
		if(fq != null){
			if (fq != null) {
	            for (int i = 0; i < fq.length; i++) {
	                String fq_str = fq[i];
	                if (fq[i].indexOf("year:\"[") != -1) {
	                    fq_str = fq[i].replaceAll("\"", "");
	                }
	                query.addFilterQuery(fq_str);
	            }
	        }
		}
		
		query.set("stats", true);
		for (int i = 0; i < statisticsField.length; i++) {
			query.add("stats.field", statisticsField[i]);
		}
		if(statisticsFacetField != null){
			for (int i = 0; i < statisticsFacetField.length; i++) {
				query.add("stats.facet", statisticsFacetField[i]);
			}
		}
		query.set("wt", "json");
		query.addField(statisticsFacetField[0]);
		
		QueryResponse response = this._SolrClient.query(query);//查询并返回结果
		Map<String,FieldStatsInfo> resultMap = response.getFieldStatsInfo();
		FieldStatsInfo statsInfo = null;
		Map<String,Map<String, Map<Object, Map<Object,Object>>>> map = new HashMap<String, Map<String,Map<Object,Map<Object,Object>>>>();
		Map<String, Map<Object, Map<Object,Object>>> facetMapResult = null;;
		Map<Object, Map<Object,Object>> mapList = null;
		Map<Object, Object> fMap = null;
		Map<String,List<FieldStatsInfo>> facetMap = null;
		List<FieldStatsInfo> fieldStatsInfoList = null;
		FieldStatsInfo fieldStatsInfo = null;
		for (String string : resultMap.keySet()) {
			statsInfo = resultMap.get(string);
			if(statisticsFacetField != null){
				facetMap = statsInfo.getFacets();
				if(facetMap!=null){
					facetMapResult = new HashMap<String, Map<Object,Map<Object,Object>>>();
					for (String str : facetMap.keySet()) {
						mapList = new HashMap<Object, Map<Object,Object>>();
						fieldStatsInfoList = facetMap.get(str);
						for (int j = 0; j < fieldStatsInfoList.size(); j++) {
							fieldStatsInfo = fieldStatsInfoList.get(j);
							fMap = new HashMap<Object, Object>();
							fMap.put("min", fieldStatsInfo.getMin());
							fMap.put("max", fieldStatsInfo.getMax());
							fMap.put("sum", fieldStatsInfo.getSum());
							fMap.put("count", fieldStatsInfo.getCount());
							fMap.put("missing", fieldStatsInfo.getMissing());
							fMap.put("mean", fieldStatsInfo.getMean());
							fMap.put("stddev", fieldStatsInfo.getStddev());
							mapList.put(fieldStatsInfo.getName(), fMap);
						}
						fMap = new HashMap<Object, Object>();
						fMap.put("min", statsInfo.getMin());
						fMap.put("max", statsInfo.getMax());
						fMap.put("sum", statsInfo.getSum());
						fMap.put("count", statsInfo.getCount());
						fMap.put("missing", statsInfo.getMissing());
						fMap.put("mean", statsInfo.getMean());
						fMap.put("stddev", statsInfo.getStddev());
						mapList.put("总计", fMap);
						facetMapResult.put(str, mapList);
					}
				}
				map.put(string, facetMapResult);
			}else{
				mapList = new HashMap<Object, Map<Object,Object>>();
				facetMapResult = new HashMap<String, Map<Object,Map<Object,Object>>>();
				fMap = new HashMap<Object, Object>();
				fMap.put("min", statsInfo.getMin());
				fMap.put("max", statsInfo.getMax());
				fMap.put("sum", statsInfo.getSum());
				fMap.put("count", statsInfo.getCount());
				fMap.put("missing", statsInfo.getMissing());
				fMap.put("mean", statsInfo.getMean());
				fMap.put("stddev", statsInfo.getStddev());
				mapList.put("总计", fMap);
				facetMapResult.put(statsInfo.getName(), mapList);
				map.put(string, facetMapResult);
			}
		}
		return map;
	}
	
	/**
	 * 多核心高亮查询
	 */
    @SuppressWarnings("unchecked")
	public List<LinkedHashMap<String, String>> multiCorehighLightQuery(SearchEntity searchEntity) throws SolrServerException, IOException {
        SolrQuery query = new SolrQuery();

        query.setQuery(searchEntity.getQ());

        query.setQuery(searchEntity.getQ());

		if (searchEntity.getShards() != null && searchEntity.getShards().size() > 0) {
			String shards = ArrayUtil.join(searchEntity.getShards(),",");
			query.set("shards", shards);
		}

		if (searchEntity.getFq() != null) {
			List<String> fq = searchEntity.getFq();
			for (int i = 0; i < fq.size(); i++) {
				String fq_str = fq.get(i);
				if (fq_str.indexOf("year:\"[") != -1) {
					fq_str = fq_str.replaceAll("\"", "");
				}
				query.addFilterQuery(fq_str);
			}
		}

		if (searchEntity.getHl() != null) {
			query.setHighlight(true);// 开启高亮
			query.setParam("hl.preserveMulti", true);// 高亮所有多值字段
			query.setHighlightFragsize(100000);// 每个分片的最大长度，默认是一个分片
			List<String> highlightFields = searchEntity.getHl();
			// 设置高亮字段
			for (int i = 0; i < highlightFields.size(); i++) {
				query.addHighlightField(highlightFields.get(i));
			}
			if (searchEntity.getHl_pre() != null && searchEntity.getHl_post() != null) {
				query.setHighlightSimplePre(searchEntity.getHl_pre());// 渲染标签前缀
				query.setHighlightSimplePost(searchEntity.getHl_post());// 渲染标签后缀
			}
		}
		// 排序
		if (searchEntity.getSort() != null) {
			List<String> sorts = searchEntity.getSort();
			String[] sort = null;
			for (int i = 0; i < sorts.size(); i++) {
				sort = sorts.get(i).split(":");
				if ("asc".equals(sort[1])) {
					query.addSort(sort[0], ORDER.asc);
				} else if ("desc".equals(sort[1])) {
					query.addSort(sort[0], ORDER.desc);
				}
			}
		}
		query.setStart(searchEntity.getStart());
		query.setRows(searchEntity.getRows());
		query.set("wt", "json");// 返回类型
		query.set("indent", "on");
		if (searchEntity.getFl() != null) {
			List<String> fields = searchEntity.getFl();
			for (int i = 0; i < fields.size(); i++) {
				query.addField(fields.get(i));
			}
		}
		
		QueryResponse response = this._SolrClient.query(query);// 查询并返回结果
   		SolrDocumentList documents = response.getResults();
   		String uniqueField = searchEntity.getUniqueField();
   		List<LinkedHashMap<String, String>> result = new ArrayList<LinkedHashMap<String,String>>();
   		LinkedHashMap<String, String> restultmap = null;
   		Map<String, Map<String, List<String>>> map = response.getHighlighting();
   		List<String> hl = searchEntity.getHl();
   		SolrDocument document = null;
   		Collection<String> fieldNames = null;
		for (int i = 0; i < documents.size(); i++) {
			restultmap = new LinkedHashMap<String, String>();
			document = documents.get(i);
			fieldNames = document.getFieldNames();
			for (String field : fieldNames) {
				if (hl != null && hl.contains(field) && uniqueField!=null){
					if (null != map.get(document.getFieldValue(uniqueField)).get(field)) {
						Object obj = document.getFieldValue(field);
						if(obj instanceof List){
							restultmap.put(field, ArrayUtil.join(map.get(document.getFieldValue(uniqueField)).get(field),";;"));
						}else{
							restultmap.put(field, map.get(document.getFieldValue(uniqueField)).get(field).get(0).toString());
						}
					}else {
						restultmap.put(field, "");
					}
				}else{
					if (null != document.getFieldValues(field)) {
						Object obj = document.getFieldValue(field);
						if(obj instanceof List){
							restultmap.put(field, ArrayUtil.join(obj,";;"));
						}else{
							restultmap.put(field, obj.toString());
						}
					}else{
						restultmap.put(field, "");
					}
				}
			}
			result.add(restultmap);
		}
        return result;
    }

    /**
   	 * 自定义权重高亮查询
   	 */
   	@SuppressWarnings("unchecked")
	public List<LinkedHashMap<String, String>> multiCoreDefTypehighLightQuery(
			SearchEntity searchEntity) throws SolrServerException, IOException {

		SolrQuery query = new SolrQuery();

		query.setQuery(searchEntity.getQ());

		if (searchEntity.getShards() != null
				&& searchEntity.getShards().size() > 0) {
			String shards = ArrayUtil.join(searchEntity.getShards(), ",");
			query.set("shards", shards);
		}

		if (searchEntity.getFq() != null) {
			List<String> fq = searchEntity.getFq();
			for (int i = 0; i < fq.size(); i++) {
				String fq_str = fq.get(i);
				if (fq_str.indexOf("year:\"[") != -1) {
					fq_str = fq_str.replaceAll("\"", "");
				}
				query.addFilterQuery(fq_str);
			}
		}

		if (searchEntity.getHl() != null) {
			query.setHighlight(true);// 开启高亮
			query.setParam("hl.preserveMulti", true);// 高亮所有多值字段
			query.setHighlightFragsize(100000);// 每个分片的最大长度，默认是一个分片
			List<String> highlightFields = searchEntity.getHl();
			// 设置高亮字段
			for (int i = 0; i < highlightFields.size(); i++) {
				query.addHighlightField(highlightFields.get(i));
			}
			if (searchEntity.getHl_pre() != null
					&& searchEntity.getHl_post() != null) {
				query.setHighlightSimplePre(searchEntity.getHl_pre());// 渲染标签前缀
				query.setHighlightSimplePost(searchEntity.getHl_post());// 渲染标签后缀
			}
		}
		// 排序
		if (searchEntity.getSort() != null) {
			List<String> sorts = searchEntity.getSort();
			String[] sort = null;
			for (int i = 0; i < sorts.size(); i++) {
				sort = sorts.get(i).split(":");
				if ("asc".equals(sort[1])) {
					query.addSort(sort[0], ORDER.asc);
				} else if ("desc".equals(sort[1])) {
					query.addSort(sort[0], ORDER.desc);
				}
			}
		}
		query.setStart(searchEntity.getStart());
		query.setRows(searchEntity.getRows());
		query.set("wt", "json");// 返回类型
		query.set("indent", "on");
		if (searchEntity.getFl() != null) {
			List<String> fields = searchEntity.getFl();
			for (int i = 0; i < fields.size(); i++) {
				query.addField(fields.get(i));
			}
		}

		query.set("defType", "edismax");
		if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())) {
			query.set("qf", searchEntity.getQf());
			query.set("tie", "1.0");
		}
		
		if (searchEntity.getBoost() != null
				&& !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}

		QueryResponse response = this._SolrClient.query(query);// 查询并返回结果
		SolrDocumentList documents = response.getResults();
		String uniqueField = searchEntity.getUniqueField();
		List<LinkedHashMap<String, String>> result = new ArrayList<LinkedHashMap<String, String>>();
		LinkedHashMap<String, String> restultmap = null;
		Map<String, Map<String, List<String>>> map = response.getHighlighting();
		List<String> hl = searchEntity.getHl();
		SolrDocument document = null;
		Collection<String> fieldNames = null;
		for (int i = 0; i < documents.size(); i++) {
			restultmap = new LinkedHashMap<String, String>();
			document = documents.get(i);
			fieldNames = document.getFieldNames();
			for (String field : fieldNames) {
				if (hl != null && hl.contains(field) && uniqueField != null) {
					if (null != map.get(document.getFieldValue(uniqueField))
							.get(field)) {
						Object obj = document.getFieldValue(field);
						if (obj instanceof List) {
							restultmap.put(field, ArrayUtil.join(
									map.get(document.getFieldValue(uniqueField))
											.get(field),
									";;"));
						} else {
							restultmap.put(field,
									map.get(document.getFieldValue(uniqueField))
											.get(field).get(0).toString());
						}
					} else {
						restultmap.put(field, "");
					}
				} else {
					if (null != document.getFieldValues(field)) {
						Object obj = document.getFieldValue(field);
						if (obj instanceof List) {
							restultmap.put(field,
									ArrayUtil.join(obj, ";;"));
						} else {
							restultmap.put(field, obj.toString());
						}
					} else {
						restultmap.put(field, "");
					}
				}
			}
			result.add(restultmap);
		}
		return result;
	}
   	
   	/**
   	 * 多核心计算自定义查询总数
   	 */
   	public int multiCoreDefTypeSearchCount(SearchEntity searchEntity) throws SolrServerException, IOException {

   		SolrQuery query = new SolrQuery();

		query.setQuery(searchEntity.getQ());

		if (searchEntity.getShards() != null
				&& searchEntity.getShards().size() > 0) {
			String shards = ArrayUtil.join(searchEntity.getShards(), ",");
			query.set("shards", shards);
		}

		if (searchEntity.getFq() != null) {
			List<String> fq = searchEntity.getFq();
			for (int i = 0; i < fq.size(); i++) {
				String fq_str = fq.get(i);
				if (fq_str.indexOf("year:\"[") != -1) {
					fq_str = fq_str.replaceAll("\"", "");
				}
				query.addFilterQuery(fq_str);
			}
		}

		query.set("wt", "json");// 返回类型

		query.set("defType", "edismax");
		if (searchEntity.getQf() != null && !"".equals(searchEntity.getQf())) {
			query.set("qf", searchEntity.getQf());
			query.set("tie", "1.0");
		}
		
		if (searchEntity.getBoost() != null && !"".equals(searchEntity.getBoost())) {
			query.set("boost", searchEntity.getBoost());
		}
		// 查询并返回结果
		QueryResponse response = _SolrClient.query(query);
		return (int) response.getResults().getNumFound();
    }
    
    /**
     * 多核心计算查询总数
     */
    public int multiCoreSearchCount(SearchEntity searchEntity) throws SolrServerException, IOException {
        SolrQuery query = new SolrQuery();

        query.setQuery(searchEntity.getQ());

		if (searchEntity.getShards() != null && searchEntity.getShards().size() > 0) {
			String shards = ArrayUtil.join(searchEntity.getShards(),",");
			query.set("shards", shards);
		}

		if (searchEntity.getFq() != null) {
			List<String> fq = searchEntity.getFq();
			for (int i = 0; i < fq.size(); i++) {
				String fq_str = fq.get(i);
				if (fq_str.indexOf("year:\"[") != -1) {
					fq_str = fq_str.replaceAll("\"", "");
				}
				query.addFilterQuery(fq_str);
			}
		}
        query.set("wt", "json");//返回类型
        QueryResponse response = this._SolrClient.query(query);//查询并返回结果
        return (int) response.getResults().getNumFound();
    }
    

    /**
     * 更新数据列表
     *
     * @param maps 需要更新的数据列表
     */
    public void updateDataList(List<Map<String, Object>> maps) throws IOException, SolrServerException {
        List<SolrInputDocument> docs = new ArrayList<>();
        SolrInputDocument solrDoc;
        for (Map<String, Object> map : maps) {
            solrDoc = new SolrInputDocument();
            for (String key : map.keySet()) {
                solrDoc.setField(key, map.get(key) == null ? "" : String.valueOf(map.get(key)));
            }
            docs.add(solrDoc);
        }
        this._SolrClient.add(docs);
        this._SolrClient.commit();
    }

    /**
     * 更新数据列表
     *
     * @param maps          需要更新的数据列表
     * @param segmentFields 需要分词的字段
     */
    public void updateDataList(List<Map<String, Object>> maps, String[] segmentFields) throws IOException, SolrServerException {
        List<SolrInputDocument> docs = new ArrayList<>();
        SolrInputDocument solrDoc;
        String[] segments;
        boolean isValNull;
        for (Map<String, Object> map : maps) {
            solrDoc = new SolrInputDocument();
            for (String key : map.keySet()) {
                isValNull = map.get(key) == null;
                if (segmentFields.length > 0 && ArrayUtil.contains(segmentFields, key)) {
                    segments = isValNull ? new String[]{} : String.valueOf(map.get(key)).split(";;");
                    if (segments.length > 0) {
                        for (String segment : segments) {
                            solrDoc.addField(key, segment);
                        }
                    } else {
                        solrDoc.setField(key, "");
                    }
                } else {
                    solrDoc.setField(key, isValNull ? "" : String.valueOf(map.get(key)));
                }
            }
            docs.add(solrDoc);
        }
        this._SolrClient.add(docs);
        this._SolrClient.commit();
    }

    /**
     * 根据查询条件删除索引
     *
     * @param query 查询条件
     */
    public void deleteByQuery(String query) throws IOException, SolrServerException {
    	this._SolrClient.deleteByQuery(query);
    	this._SolrClient.commit();
    }
}
 
